<?php


namespace app\common\model\xiluedu;


use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\Model;
use function fast\array_get;

class CourseCode extends Model
{
    // 表名
    protected $name = 'xiluedu_course_code';

    // 追加属性
    protected $append = [

    ];

    public function course(){
        return $this->belongsTo('Course','course_id','id',[],'left');
    }

    /**
     * 兑换码搜索课程列表
     * @param $course_code
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public static function codeCourse($course_code){

        return static::field('id,course_id,code')->with(['course'=>function($query){
            $query->where('status','1')->withField('id,type,name,category_id,tag_ids,teacher_id,thumb_image,description,is_charge,(basic_num+real_num) total_num,collection_count,play_count,salesprice') ->order('weigh','desc');
        }])
            ->where('code',$course_code)
            ->select();
    }

    /**
     *兑换
     */
    public static function exchangeCourse($course_code,$course_code_id,$user_id){
        $row = static::where('code',$course_code)->find();
        if(!$row){
            throw new Exception("当前课程不支持兑换");
        }
        if($row->id != $course_code_id){
            throw new Exception("当前码与兑换课程不一致");
        }
        if( $row->use_status == 1){
            throw new Exception("当前课程已被兑换");
        }
        if(!$row->course || $row->course->status == 0){
            throw new Exception("当前课程不存在或已下架");
        }
        if(UserCourse::where('user_id',$user_id)->where('course_id',$row->course_id)->count()>0){
            throw new Exception("您已拥有当前课程");
        }
        Db::transaction(function () use($user_id,$row){
            UserCourse::create([
                'from_type' =>  2,
                'user_id'   =>  $user_id,
                'course_id' =>  $row->course_id
            ]);
            $row->use_status = 1;
            $row->user_id = $user_id;
            $row->save();
        });
        return true;
    }

}